package com.yunkaweilai.android.activity.shop;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import com.classic.common.MultipleStatusView;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.shop.ShopTypeModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.shop.ShopTypeMaxDialog;
import com.yunkaweilai.android.view.dialog.shop.ShopTypeMinDialog;
import com.yunkaweilai.android.view.dialog.shop.ShopTypeUpdateDialog1;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商品选择分类
 * Created by Administrator on 2017/6/15.
 */

public class ShopTypeActivity extends BaseActivity {

    @BindView(R.id.id_btn_add_max)
    Button idBtnAddMax;
    @BindView(R.id.id_left_listView)
    ListView idLeftListView;
    @BindView(R.id.id_btn_add_min)
    Button idBtnAddMin;
    @BindView(R.id.id_right_listView)
    ListView idRightListView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    private CommonAdapter<ShopTypeModel> leftAdapter;
    private CommonAdapter<ShopTypeModel> rightAdapter;
    private ArrayList<ShopTypeModel> AllTypeList = new ArrayList<>();
    private ArrayList<ShopTypeModel> rightList = new ArrayList<>();
    private JSONObject listJson;//各种分类的列表
    private int selector = -1;//左侧选中的position
    public static final String SHOP_TYPE_NAME = "SHOP_TYPE_NAME";
    public static final String SHOP_TYPE_ID = "SHOP_TYPE_ID";
    private ShopTypeMaxDialog maxDialog;
    private ShopTypeMinDialog minDialog;
    private ShopTypeUpdateDialog1 updateDialog;
    public static final String SHOP_TYPE_URL = "SHOP_TYPE_URL";
    private String shop_type_url = "";
    private String shop_type = "";
    public static final String SHOP_TYPE = "SHOP_TYPE";
    public static final String PT_SHOP = "PT_SHOP";
    public static final String TIME_SHOP = "TIME_SHOP";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_type);
        ButterKnife.bind(this);
        shop_type_url = getIntent().getStringExtra(SHOP_TYPE_URL);
        shop_type = getIntent().getStringExtra(SHOP_TYPE);
        idMultipleStatusView.showLoading();
        new TitleBuilder(this).setLeftImage(R.mipmap.ic_go_back)
                .setTitleText("商品分类")
                .setRightText("确定");
        initAdapter();
        initClick();
        initHttp();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        //注册事件
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTypeEvent(Event.TypeEvent typeEvent) {
        if (typeEvent.type == CommonConstants.MAX_TYPE) {
            if (typeEvent.flag) {
                idMultipleStatusView.showLoading();
                selector = -1;
                initHttp();
            }
        }
    }

    private void setSelector(int position){
        for (int i = 0; i < AllTypeList.size(); i++) {
            if (i == position){
                AllTypeList.get(i).setUpdate(true);
            }else{
                AllTypeList.get(i).setUpdate(false);
            }
        }
    }

    private void initClick() {
        idLeftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selector = position;
                setSelector(position);
                rightList.clear();
                rightList.addAll(getJsonList(AllTypeList.get(position).getGoods_category_id()));
                rightAdapter.notifyDataSetChanged();
                leftAdapter.notifyDataSetChanged();//修改左侧选中的状态
            }
        });

        idRightListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.putExtra(SHOP_TYPE_NAME, rightList.get(position).getGoods_category_name());
                intent.putExtra(SHOP_TYPE_ID, rightList.get(position).getGoods_category_id());
                setResult(RESULT_OK, intent);
                finish();
            }
        });


    }

    private void initAdapter() {

        leftAdapter = new CommonAdapter<ShopTypeModel>(this, R.layout.item_list_left_type_update, AllTypeList) {
            @Override
            protected void convert(ViewHolder viewHolder, final ShopTypeModel item, int position) {
                viewHolder.setText(R.id.id_tv_name, item.getGoods_category_name() + "");
                ImageView imgUpdate = viewHolder.getView(R.id.id_img_update);
                if (item.isUpdate()) {
                    viewHolder.getConvertView().setBackgroundColor(getResources().getColor(R.color.bg_white));
                    imgUpdate.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.getConvertView().setBackgroundColor(getResources().getColor(R.color.wjx_type_list_bg));
                    imgUpdate.setVisibility(View.GONE);
                }

                imgUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        updateDialog = new ShopTypeUpdateDialog1(ShopTypeActivity.this,R.style.dialog, item.getGoods_category_id(), item.getGoods_category_name(), "0",shop_type);
                        updateDialog.show();
                        updateDialog.setCanceledOnTouchOutside(false);
                    }
                });
            }
        };
        rightAdapter = new CommonAdapter<ShopTypeModel>(this, R.layout.item_list_left_type_update, rightList) {
            @Override
            protected void convert(ViewHolder viewHolder, final ShopTypeModel item, int position) {
                viewHolder.setText(R.id.id_tv_name, item.getGoods_category_name() + "");
                ImageView imgUpdate = viewHolder.getView(R.id.id_img_update);
                imgUpdate.setImageResource(R.mipmap.ic_update_type);
                imgUpdate.setVisibility(View.VISIBLE);
                imgUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        updateDialog = new ShopTypeUpdateDialog1(ShopTypeActivity.this,R.style.dialog, item.getGoods_category_id(), item.getGoods_category_name(), AllTypeList.get(selector).getGoods_category_id(),shop_type);
                        updateDialog.show();
                        updateDialog.setCanceledOnTouchOutside(false);
                    }
                });
            }
        };
        idLeftListView.setAdapter(leftAdapter);
        idRightListView.setAdapter(rightAdapter);
    }

    private void initHttp() {
        HttpRequest.postUrl(shop_type_url)
                .log(TAG).execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(String json) {
                boolean checkCode = Utils.checkCode(ShopTypeActivity.this, json);
                if (checkCode) {
                    idMultipleStatusView.showContent();
                    initJson(json);
                    leftAdapter.notifyDataSetChanged();
                    if (AllTypeList.size() > 0) {
                        rightList.clear();
                        rightList.addAll(getJsonList(AllTypeList.get(0).getGoods_category_id()));
                        rightAdapter.notifyDataSetChanged();
                    }
                } else {
                    idMultipleStatusView.showError();
                }
            }

            @Override
            public void onError(Exception e) {
                idMultipleStatusView.showError();
            }
        });
    }

    private ArrayList<ShopTypeModel> getJsonList(String type) {
        ArrayList<ShopTypeModel> mylist = new ArrayList<>();
        JSONArray jsonArray = null;
        try {
            jsonArray = listJson.getJSONArray(type);
            for (int i = 0; i < jsonArray.length(); i++) {
                ShopTypeModel typeModel = new ShopTypeModel();
                JSONObject index = jsonArray.getJSONObject(i);
                typeModel.setGoods_category_id(index.getString("goods_category_id"));
                typeModel.setGoods_category_name(index.getString("goods_category_name"));
                mylist.add(typeModel);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mylist;
    }

    private void initJson(String typeJson) {
        try {
            JSONObject jsonObject = new JSONObject(typeJson);
            JSONObject dataJson = jsonObject.getJSONObject("data");
            listJson = dataJson.getJSONObject("list");
            JSONArray jsonArray = listJson.getJSONArray("0");
            AllTypeList.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                ShopTypeModel typeModel = new ShopTypeModel();
                JSONObject index = jsonArray.getJSONObject(i);
                typeModel.setGoods_category_id(index.getString("goods_category_id"));
                typeModel.setGoods_category_name(index.getString("goods_category_name"));
                typeModel.setUpdate(i == 0);//第一个的时候，标记选中
                selector = 0;
                AllTypeList.add(typeModel);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.id_btn_add_max, R.id.id_btn_add_min, R.id.titlebar_iv_left,R.id.titlebar_tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_tv_right://标题右边按钮
                if (selector == -1) {
                    Intent intent = new Intent();
                    intent.putExtra(SHOP_TYPE_NAME, "");
                    intent.putExtra(SHOP_TYPE_ID, "");
                    setResult(RESULT_OK, intent);
                }else{
                    Intent intent = new Intent();
                    intent.putExtra(SHOP_TYPE_NAME, AllTypeList.get(selector).getGoods_category_name());
                    intent.putExtra(SHOP_TYPE_ID, AllTypeList.get(selector).getGoods_category_id());
                    setResult(RESULT_OK, intent);
                }

                finish();
                break;
            case R.id.id_btn_add_max://大分类
                maxDialog = new ShopTypeMaxDialog(this,shop_type);
                maxDialog.show();
                maxDialog.setCanceledOnTouchOutside(false);
                break;
            case R.id.id_btn_add_min://小分类
                if (AllTypeList.size() > 0) {
                    ShopTypeModel shopTypeModel = AllTypeList.get(selector);
                    minDialog = new ShopTypeMinDialog(this, shopTypeModel.getGoods_category_id(), shopTypeModel.getGoods_category_name(),shop_type);
                    minDialog.show();
                    minDialog.setCanceledOnTouchOutside(false);
                }else{
                    showToast("还未添加大分类");
                }
                break;
            case R.id.titlebar_iv_left:
                finish();
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册事件
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }
}
